package com.ggs.rg.ybjb.usermodule.listener;


import com.ggs.rg.ybjb.usermodule.mapper.TOrderMapper;
import com.ggs.rg.ybjb.usermodule.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    TOrderMapper tOrderMapper;

    @Resource(name="myRedisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RedisUtil redisUtil;            //自己写的操作redis的工具类,其实就是封装了redisTemplate的操作

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对 redis 数据失效事件，进行数据处理
     *
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取到失效的 key
        String orderNo = message.toString();
        System.out.println("获取到的失效key为:"+orderNo);
        //判断过期的key是否为需要进行过期处理
        //订单的key需要进行,key值包含order,key格式为:orderStatus+oid
        //为什么要设置这样的格式?orderStatus标记为订单相关的key,oid为保证每个订单标志在缓存中都唯一
        if (orderNo.startsWith("order")) {
            //因为订单标记key为两部分组成,所以进行切割，取出oid部分
            String[] split = orderNo.split("\\.");
            System.out.println("==========>"+split[1]);
            int result = tOrderMapper.deleteById(split[1]);
            if (result == 1){
                System.out.println("订单已过期");
            }else {
                System.out.println("更新订单失败!!!");
            }
        }
    }
}
